package com.starchen.optimalselection.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starchen.optimalselection.common.model.ResultPage;
import com.starchen.optimalselection.common.utils.PageUtils;
import com.starchen.optimalselection.common.mapper.CategoryMapper;
import com.starchen.optimalselection.common.mapper.SkuInfoMapper;
import com.starchen.optimalselection.common.model.Category;
import com.starchen.optimalselection.common.model.SkuImages;
import com.starchen.optimalselection.common.model.SkuInfo;
import com.starchen.optimalselection.common.model.SpuInfoDesc;
import com.starchen.optimalselection.common.model.form.SkuInfoQueryForm;
import com.starchen.optimalselection.common.model.vo.ItemAttrGroupWithAttrVO;
import com.starchen.optimalselection.common.model.vo.ItemSaleAttrVO;
import com.starchen.optimalselection.common.service.AttributeValueService;
import com.starchen.optimalselection.common.service.SkuImagesService;
import com.starchen.optimalselection.common.service.SkuSaleAttrValueService;
import com.starchen.optimalselection.common.service.SpuInfoDescService;
import com.starchen.optimalselection.web.model.vo.ItemDetailVO;
import com.starchen.optimalselection.web.service.ProductService;
import com.starchen.optimalselection.web.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品Service实现类
 * Created by daxilong on 2020/4/6.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttributeValueService attributeValueService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public ResultPage page(SkuInfoQueryForm params) {
        Long categoryId =  params.getCategoryId();
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        if(categoryId != null){
            queryWrapper.eq("category_id",categoryId);
        }
        IPage<SkuInfo> page = skuInfoMapper.selectPage(PageUtils.getPage(params.getPageIndex(),params.getPageSize()), queryWrapper);
        return new ResultPage(page);
    }

    /**
     * value 为缓存分区名字，即redis中的目录 还为key的前缀
     * 默认key为自动生成
     * 指定后为 category::treelist
     * 默认ttl为-1，需在配置文件中设置缓存存活时间
     * 默认为jdk序列化方式保存
     * @return
     */
    @Cacheable(value = {"category"},key = "'treelist'")
    @Override
    public List<Category> getCategoryTreeList() {
        List<Category> allCategoryList = categoryMapper.selectList(null);

        List<Category> categoryList = allCategoryList.stream().filter(category -> category.getParentId() == 0).map(category -> {
            category.setChildren(getCategoryChildred(allCategoryList,category));
            return category;
        }).sorted(Comparator.comparing(Category::getSort)).collect(Collectors.toList());
        return categoryList;
    }

    private List<Category> getCategoryChildred(List<Category> allEntity, Category rootCategory){
        List<Category> categoryList = allEntity.stream().filter(category -> category.getParentId() == rootCategory.getId()).map(category -> {
            category.setChildren(getCategoryChildred(allEntity,category));
            return category;
        }).sorted(Comparator.comparing(Category::getSort)).collect(Collectors.toList());
        return  categoryList;
    }

    @Override
    public ItemDetailVO getSkuInfo(Long skuId) {
        ItemDetailVO itemDetailVO = new ItemDetailVO();
        //1.sku基本信息
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        itemDetailVO.setSkuInfo(skuInfo);

        // 2.此sku的图片集
        List<SkuImages> skuImagesEntities = skuImagesService.listBySkuId(skuId);
        itemDetailVO.setSkuImages(skuImagesEntities);

        // 3.同商品所有销售销售属性及其对应值
        List<ItemSaleAttrVO> saleAttrs = skuSaleAttrValueService.allAttrValueWithSkuBySpuId(skuInfo.getSpuId());
        itemDetailVO.setSaleAttrs(saleAttrs);

        // 4.商品描述信息(spu) 大图
        SpuInfoDesc spuInfoDescEntity = spuInfoDescService.getById(skuInfo.getSpuId());
        itemDetailVO.setSpuDesc(spuInfoDescEntity);

        // 5.商品规格参数(spu，属性分组与属性)
        List<ItemAttrGroupWithAttrVO> itemAttrGroupWithAttrVOS = attributeValueService.getAttrsWithAttrGroupBySpuId(skuInfo.getSpuId());
        itemDetailVO.setSpuAttrGroups(itemAttrGroupWithAttrVOS);

        //6.商品是否有库存
        Long stock = wareSkuService.getSkuStock(skuId);
        itemDetailVO.setHasStock(stock > 0);

        return itemDetailVO;
    }


    /**
     * 初始对象转化为节点对象
     */

//    private PmsProductCategoryNode covert(PmsProductCategory item, List<PmsProductCategory> allList) {
//        PmsProductCategoryNode node = new PmsProductCategoryNode();
//        BeanUtils.copyProperties(item, node);
//        List<PmsProductCategoryNode> children = allList.stream()
//                .filter(subItem -> subItem.getParentId().equals(item.getId()))
//                .map(subItem -> covert(subItem, allList)).collect(Collectors.toList());
//        node.setChildren(children);
//        return node;
//    }

}
